package com.wing.product.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.product.dao.WarehouseProductionSchedulingPlanDao;
import com.wing.product.dao.WarehouseProductionSchedulingPlanDetailDao;
import com.wing.product.model.entity.WarehouseProductionOrder;
import com.wing.product.model.entity.WarehouseProductionOrderDetail;
import com.wing.product.model.entity.WarehouseProductionSchedulingPlan;
import com.wing.product.model.entity.WarehouseProductionSchedulingPlanDetail;
import com.wing.product.model.response.WarehouseProductionSchedulingPlanDetailVO;
import com.wing.product.model.response.WarehouseProductionSchedulingPlanVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class WarehouseProductionSchedulingPlanServiceImpl extends ServiceImpl<WarehouseProductionSchedulingPlanDao, WarehouseProductionSchedulingPlan> implements WarehouseProductionSchedulingPlanService{

    @Autowired
    WarehouseProductionSchedulingPlanDetailDao warehouseProductionSchedulingPlanDetailDao;
    @Autowired
    WarehouseProductionSchedulingPlanDetailService warehouseProductionSchedulingPlanDetailService;
    @Autowired
    WarehouseProductionOrderService warehouseProductionOrderService;

    @Autowired
    WarehouseProductionOrderDetailService warehouseProductionOrderDetailService;

    @Override
    public Page<WarehouseProductionSchedulingPlanVO> pageList4app(Page page, Map<String, Object> params) {
        List<WarehouseProductionSchedulingPlanVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public WarehouseProductionSchedulingPlanVO selectProductionSchedulingPlanDetail(String id){

        WarehouseProductionSchedulingPlanVO warehouseProductionSchedulingPlanVO = this.baseMapper.selectProductionSchedulingPlanDetail(id);
        LambdaQueryWrapper<WarehouseProductionSchedulingPlanDetail> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(WarehouseProductionSchedulingPlanDetail::getWarehouseProductionSchedulingPlanId,id)
                .eq(WarehouseProductionSchedulingPlanDetail::getIsDeleted,0);
        List<WarehouseProductionSchedulingPlanDetail> warehouseProductionSchedulingPlanDetails = warehouseProductionSchedulingPlanDetailDao.selectList(lambdaQueryWrapper);
        warehouseProductionSchedulingPlanVO.setWarehouseProductionSchedulingPlanDetailList(warehouseProductionSchedulingPlanDetails);
        return warehouseProductionSchedulingPlanVO;
    }

    @Override
    @Transactional
    public JsonResult saveWarehouseProductionSchedulingPlan(WarehouseProductionSchedulingPlanVO warehouseProductionSchedulingPlanVO) {

        //添加生产计划
        if (ObjectUtil.isNotEmpty(warehouseProductionSchedulingPlanVO)) {

            //计划生产数量总和
            Integer scheduleSum = 0;

            WarehouseProductionSchedulingPlan warehouseProductionSchedulingPlan = new WarehouseProductionSchedulingPlan();
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(WarehouseProductionSchedulingPlan.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(warehouseProductionSchedulingPlanVO, warehouseProductionSchedulingPlan, copyOptions);
            warehouseProductionSchedulingPlan.setProductionPlanCode(UniqueIdGeneratorUtil.generateUniqueId("SCJH", "yyyyMMddHHmmss", 1000, 9999));
            warehouseProductionSchedulingPlan.setStatus("1");
            this.baseMapper.insert(warehouseProductionSchedulingPlan);

            //添加生产计划明细
            List<WarehouseProductionSchedulingPlanDetail> warehouseProductionSchedulingPlanDetailList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(warehouseProductionSchedulingPlanVO.getWarehouseProductionSchedulingPlanDetailListVO())) {

                LambdaUpdateWrapper<WarehouseProductionOrder> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.eq(WarehouseProductionOrder::getId,warehouseProductionSchedulingPlan.getProductionOrderId());

                for (WarehouseProductionSchedulingPlanDetailVO pd : warehouseProductionSchedulingPlanVO.getWarehouseProductionSchedulingPlanDetailListVO()) {
                    pd.setWarehouseProductionSchedulingPlanId(warehouseProductionSchedulingPlan.getId());
                    pd.setStatus("1");
                    pd.setCustomerId(warehouseProductionSchedulingPlanVO.getCustomerId());
                    pd.setCode(UniqueIdGeneratorUtil.generateUniqueId("ZLD", "yyyyMMddHHmmss", 1000, 9999));

                    WarehouseProductionSchedulingPlanDetail warehouseProductionSchedulingPlanDetail = new WarehouseProductionSchedulingPlanDetail();
                    CopyOptions cps = CopyOptions.create()
                            .setEditable(WarehouseProductionSchedulingPlanDetail.class)
                            .setIgnoreError(true)
                            .setIgnoreNullValue(true);
                    BeanUtil.copyProperties(pd, warehouseProductionSchedulingPlanDetail, cps);
                    warehouseProductionSchedulingPlanDetail.setCreateTime(LocalDateTime.now());
                    warehouseProductionSchedulingPlanDetailList.add(warehouseProductionSchedulingPlanDetail);


                    //更新生产订单
                    //判断生产数量是否大于总排产数
                    if (pd.getPlannedQuantity() >= warehouseProductionSchedulingPlanVO.getRemainingProductionSchedule()){
                        //判断生产数量是否小于需求数
                        if(pd.getPlannedQuantity() <= pd.getRequiredQuantity()){
//                            lambdaUpdateWrapper.set(WarehouseProductionOrder::getRemainingProductionSchedule,0)
//                                    .set(WarehouseProductionOrder::getStatus,"3");
                            scheduleSum = 0;
                        }else {
                            //判断总排产数是否大于需求数
                            if (warehouseProductionSchedulingPlanVO.getRemainingProductionSchedule() > pd.getRequiredQuantity()){
//                                lambdaUpdateWrapper.set(WarehouseProductionOrder::getRemainingProductionSchedule,warehouseProductionSchedulingPlanVO.getRemainingProductionSchedule() - pd.getRequiredQuantity());
                                if (scheduleSum == 0){
                                    scheduleSum = warehouseProductionSchedulingPlanVO.getRemainingProductionSchedule() - pd.getScheduleQuantity();
                                }else {
                                    scheduleSum = scheduleSum - pd.getScheduleQuantity();
                                }

                            }else {
//                                lambdaUpdateWrapper.set(WarehouseProductionOrder::getRemainingProductionSchedule,0)
//                                        .set(WarehouseProductionOrder::getStatus,"3");
                                scheduleSum = 0;
                            }
                        }
                    }else {
                        //判断生产数量是否大于需求数
                        if(pd.getPlannedQuantity() > pd.getRequiredQuantity()){
//                            lambdaUpdateWrapper.set(WarehouseProductionOrder::getRemainingProductionSchedule,warehouseProductionSchedulingPlanVO.getRemainingProductionSchedule() - pd.getRequiredQuantity());
                            if (scheduleSum == 0){
                                scheduleSum = warehouseProductionSchedulingPlanVO.getRemainingProductionSchedule() - pd.getRequiredQuantity();
                            }else {
                                scheduleSum = scheduleSum - pd.getRequiredQuantity();
                            }

                        }else {
                            //判断生产数量是否大于排产数
                            if (pd.getPlannedQuantity() > pd.getScheduleQuantity()){
//                                lambdaUpdateWrapper.set(WarehouseProductionOrder::getRemainingProductionSchedule,warehouseProductionSchedulingPlanVO.getRemainingProductionSchedule() - pd.getScheduleQuantity());
                                if (scheduleSum == 0){
                                    scheduleSum = warehouseProductionSchedulingPlanVO.getRemainingProductionSchedule() - pd.getScheduleQuantity();
                                }else {
                                    scheduleSum = scheduleSum - pd.getScheduleQuantity();
                                }
                            }else {
//                                lambdaUpdateWrapper.set(WarehouseProductionOrder::getRemainingProductionSchedule,warehouseProductionSchedulingPlanVO.getRemainingProductionSchedule() - pd.getPlannedQuantity());
                                if (scheduleSum == 0){
                                    scheduleSum = warehouseProductionSchedulingPlanVO.getRemainingProductionSchedule() - pd.getPlannedQuantity();
                                }else {
                                    scheduleSum = scheduleSum - pd.getPlannedQuantity();
                                }
                            }
                        }
                    }

                    //更新生产订单明细
                    LambdaUpdateWrapper<WarehouseProductionOrderDetail> lambdaUpdateWrapperDetail = new LambdaUpdateWrapper<>();
                    lambdaUpdateWrapperDetail.eq(WarehouseProductionOrderDetail::getId,pd.getProductionOrderDetailId())
                            .eq(WarehouseProductionOrderDetail::getIsDeleted,0);
                    //判断生产数量是否大于排产数
                    if (pd.getPlannedQuantity() >= pd.getScheduleQuantity()){
                        lambdaUpdateWrapperDetail.set(WarehouseProductionOrderDetail::getScheduleQuantity,0)
                                .set(WarehouseProductionOrderDetail::getState,2);
                    }else {
                        lambdaUpdateWrapperDetail.set(WarehouseProductionOrderDetail::getScheduleQuantity,pd.getScheduleQuantity() - pd.getPlannedQuantity());
                    }
                    warehouseProductionOrderDetailService.update(lambdaUpdateWrapperDetail);
                }
                warehouseProductionSchedulingPlanDetailService.saveBatch(warehouseProductionSchedulingPlanDetailList);

                if (scheduleSum >0){
                    lambdaUpdateWrapper.set(WarehouseProductionOrder::getRemainingProductionSchedule,scheduleSum);
                }else {
                    lambdaUpdateWrapper.set(WarehouseProductionOrder::getRemainingProductionSchedule,scheduleSum)
                            .set(WarehouseProductionOrder::getStatus,"3");
                }
                warehouseProductionOrderService.update(lambdaUpdateWrapper);
            }

            return JsonResult.success("添加成功");
        } else {
            return JsonResult.fail("添加失败");
        }
    }

    @Override
    @Transactional
    public JsonResult updateProductionSchedulingPlan(String id, String status){

        WarehouseProductionSchedulingPlan warehouseProductionSchedulingPlan = this.baseMapper.selectById(id);
        warehouseProductionSchedulingPlan.setStatus(status);
        this.baseMapper.updateById(warehouseProductionSchedulingPlan);
        LambdaQueryWrapper<WarehouseProductionSchedulingPlanDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WarehouseProductionSchedulingPlanDetail::getWarehouseProductionSchedulingPlanId,warehouseProductionSchedulingPlan.getId())
                .eq(WarehouseProductionSchedulingPlanDetail::getIsDeleted,0);
        List<WarehouseProductionSchedulingPlanDetail> warehouseProductionSchedulingPlanDetails = warehouseProductionSchedulingPlanDetailDao.selectList(lambdaQueryWrapper);
        for (WarehouseProductionSchedulingPlanDetail ps : warehouseProductionSchedulingPlanDetails){
            ps.setStatus(status);
        }
        warehouseProductionSchedulingPlanDetailService.updateBatchById(warehouseProductionSchedulingPlanDetails);
        return JsonResult.success("操作成功");
    }

    @Override
    @Transactional
    public JsonResult updateWarehouseProductionSchedulingPlan(WarehouseProductionSchedulingPlanVO warehouseProductionSchedulingPlanVO){

        if (ObjectUtil.isNotEmpty(warehouseProductionSchedulingPlanVO)){
            WarehouseProductionSchedulingPlan warehouseProductionSchedulingPlan = new WarehouseProductionSchedulingPlan();
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(WarehouseProductionSchedulingPlan.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(warehouseProductionSchedulingPlanVO, warehouseProductionSchedulingPlan, copyOptions);
            warehouseProductionSchedulingPlan.setUpdateTime(LocalDateTime.now());
            this.baseMapper.updateById(warehouseProductionSchedulingPlan);
            LambdaQueryWrapper<WarehouseProductionSchedulingPlanDetail> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.eq(WarehouseProductionSchedulingPlanDetail::getWarehouseProductionSchedulingPlanId,warehouseProductionSchedulingPlan.getId())
                    .eq(WarehouseProductionSchedulingPlanDetail::getIsDeleted,0);
            warehouseProductionSchedulingPlanDetailDao.delete(lambdaQueryWrapper);
            if (CollectionUtils.isNotEmpty(warehouseProductionSchedulingPlanVO.getWarehouseProductionSchedulingPlanDetailList())){
                for (WarehouseProductionSchedulingPlanDetail ps : warehouseProductionSchedulingPlanVO.getWarehouseProductionSchedulingPlanDetailList()){
//                    ps.setId(null);
                    ps.setWarehouseProductionSchedulingPlanId(warehouseProductionSchedulingPlan.getId());
                    ps.setUpdateTime(LocalDateTime.now());
                }
                warehouseProductionSchedulingPlanDetailService.saveBatch(warehouseProductionSchedulingPlanVO.getWarehouseProductionSchedulingPlanDetailList());
            }
            return JsonResult.success("修改成功");
        }else {
            return JsonResult.fail("修改失败");
        }
    }
}
